<template>
  <div class="container shoppingCart">
    <div class="receipt-list" v-if="defCheckedList.length>0&&cartList">
      <div class="receipt-store" v-for="(item,index) in cartList" :key="index">
        <div class="receipt-store-header">
          <label class="gxs-check">
            <i-checkbox i-class="gxs-checkbox" value=" " :checked="defCheckedList[index].store.checked" color="#ee7559"
              @change="storeChange($event,index)"></i-checkbox>
          </label>
          <span class="store-name">{{item.store_name}}</span>
        </div>
        <div class="receipt-store-body">
          <!-- <receipt-module :showChecked="true" v-for="(itemGoods,indexGoods) in item.goods" :key="indexGoods" :data="itemGoods"
            :store="item" :allChecked="checked" :change="receiptChange" :checked="isChecked(itemGoods,item)" :editNote="editNote"
            :note="getNote(itemGoods)"></receipt-module> -->
          <div class="receipt" v-for="(itemGoods,indexGoods) in item.goods" :key="indexGoods">
            <div class="receipt-header">
              <div class="receipt-check">
                <i-checkbox i-class="gxs-checkbox" color="#ee7559" :checked="defCheckedList[index].cart_ids[indexGoods].checked"
                  @change="receiptChange($event,index,indexGoods)"></i-checkbox>
              </div>
              <div class="receipt-pic">
                <img mode="widthFix" :src="itemGoods.goods_logo" />
              </div>
              <div class="receipt-info">
                <p class="receipt-title">{{itemGoods.goods_name}} {{itemGoods.goods_sn}}</p>
                <div class="receipt-note">
                  <p class="receipt-note-type">规格：</p>
                  <p class="receipt-note-describe">
                    <span>
                      <span>{{itemGoods.spec_key_name}}</span>
                    </span>
                    <i-icon type="enter" />
                  </p>
                </div>
                <div class="receipt-des">
                  <p class="receipt-price">￥{{itemGoods.goods_price}}</p>
                  <p class="receipt-nst">x{{itemGoods.goods_num}}</p>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="receipt-nav" v-if="cartList&&cartList.length&&cartList.length>0">
      <div class="receipt-control">
        <label class="gxs-check">
          <i-checkbox i-class="gxs-checkbox" value="全选" color="#ee7559" :checked="checked" @change="handleFruitChange"></i-checkbox>
        </label>
        <div class="delete" @click="delMallCart">删除</div>
      </div>
      <div class="receipt-settlement">
        <p class="total">合计：<span class="price">￥{{price}}</span></p>
        <i-button type="primary" size="small" :disabled="price<=0" i-class="settlement-btn" @click="settlement" shape="circle">结算</i-button>
      </div>
    </div>
    <div v-else>
      <i-load-more tip="购物车暂无商品" :loading="loading" />
    </div>
    <i-toast id="toast" />
    <van-dialog use-slot :show="noteShow" show-cancel-button showConfirmButton @close="close" @confirm="confirmNote"
      @cancel="close">
      <textarea placeholder="请输入备注" @change="dialogTextarea($event)" class="dialog-textarea"></textarea>
    </van-dialog>
  </div>
</template>

<script>
  import {
    mapState,
    mapMutations
  } from "Vuex";
  // 依赖
  const {
    $Toast
  } = require('@/../static/iview/base/index');
  import Dialog from "@/../static/vant/dialog/dialog";
  import receiptModule from "@/components/receiptModule";
  import request from "@/api/request";
  export default {
    components: {
      receiptModule
    },
    data() {
      return {
        noteShow: false,
        noteText: '',
        note: [],
        checked: false,
        price: 0,
        eaitData: null,
        storeList: [],
        defCheckedList: [],
      }
    },
    computed: {
      ...mapState(['cartList', 'checkedList'])
    },
    methods: {
      ...mapMutations(['setCartList', 'setCheckedList', 'setNoteList', 'setCheckedNoteList']),
      close() {
        // this.noteShow = false
      },
      settlement() {
        console.log("结算按钮")
        this.setCheNoteList()
        if (this.checkedList.length > 0) {
          this.$router.push({
            path: '/pages/settlement/settlement'
          })
        }
      },
      getNote(data) {
        // for (let i = 0; i < this.note.length; i++) {
        //   for (let attr in this.note[i]) {
        //     if (data.cart_id == attr) {
        //       return this.note[i][attr]
        //     }
        //   }
        // }
      },
      dialogTextarea(e) {
        // //console.log(e.mp.detail.value)
        // this.noteText = e.mp.detail.value
        // //console.log(this.noteText)
      },
      isNote() {
        // //console.log('调试的内容')
        // //console.log(this.note)
        // return new Promise((resolve, reject) => {
        //   let isNote = false
        //   for (let i = 0; i < this.note.length; i++) {
        //     for (let a in this.note[i]) {
        //       //console.log(this.eaitData.cart_id, a)
        //       if (this.eaitData.cart_id == a) {
        //         isNote = true
        //         resolve([i, a])
        //         break;
        //       }
        //     }
        //   }
        //   if (!isNote) {
        //     reject()
        //   }
        // })
      },
      editNote(data) {
        // // 增加note的商品
        // this.eaitData = data
        // // 打开编辑的窗口
        // this.noteShow = true
        // // 判断当前商品是否已经有note
        // this.isNote().then((attr) => {
        //   // 已经有了note，将文字放到弹窗的输入框里
        //   this.noteText = this.note[attr[0]][attr[1]]
        // }).catch((error) => {
        //   // 没有note，弹窗的输入框内容为空
        //   //console.log(error)
        //   this.noteText = ''
        // })
      },

      confirmNote() {
        // //console.log('点击确认以后')
        // // 编辑完成以后，点击确认按钮，判断是否是编辑note
        // this.isNote().then((attr) => {
        //   // 是编辑，新增一个obj并且将内容更新到 this.note 
        //   let obj = {}
        //   obj[this.eaitData.cart_id] = this.noteText
        //   this.$set(this.note, attr[0], obj)
        // }).catch(() => {
        //   // 是新增 push 到 note 里
        //   //console.log(this)
        //   //console.log(this.noteText)
        //   if (this.noteText.length > 0) {
        //     let obj = {}
        //     obj[this.eaitData.cart_id] = this.noteText
        //     this.note.push(obj)
        //   }
        // })
        // //console.log('最新的note')
        // //console.log(this.note)
        // // 更新nodelist
        // this.setNoteList(this.note)
        // // this.noteText = ''
        // this.setCheNoteList()
      },
      getMallCartList() {
        request.getMallCartList({
            page: 1,
            page_num: 9999,
          })
          .then(res => {
            //console.log(res.data)
            this.getCheckedList(res.data)
            //console.log(85221)
            //console.log(this.checkedList)
            this.setCartList(res.data)
            //console.log(9999)
            //console.log(this.cartList)
          });
      },
      getCheckedList(data) {
        let ary = []
        data.map((item, index) => {
          //console.log(item)
          let obj = {}
          obj.store = {
            store_id: item.store_id,
            checked: false
          }
          obj.cart_ids = []
          item.goods.map(goods => {
            obj.cart_ids.push({
              cart_id: goods.cart_id,
              checked: false
            })
          })
          ary.push(obj)
        })
        //console.log(ary)
        this.defCheckedList = ary
        // this.setCheckedList(ary)
      },
      delMallCart() {
        let ary = []
        this.checkedList.map(item => {
          ary = ary.concat(item.cart_ids)
        })
        request.delMallCart({
          cart_id: ary + ''
        }).then(res => {
          $Toast({
            content: res.message,
            type: res.code == 0 ? 'success' : 'warning'
          });
          this.setCheckedList([])
          this.getMallCartList()
        }).catch(res => {
          $Toast({
            content: res.message,
            type: res.code == 0 ? 'success' : 'warning'
          });
        })
      },
      handleFruitChange(e) {
        let checked = e.mp.detail.current
        let ary = this.defCheckedList
        ary.map(item => {
          item.store.checked = checked
          item.cart_ids.map(goods => {
            goods.checked = checked
          })
        })
        this.defCheckedList = []
        this.defCheckedList = ary
        // if (e.mp.detail.current) {
        //   let ary = []
        //   this.cartList.map((item) => {
        //     item.goods.map((t) => {
        //       ary.push(t.cart_id)
        //     })
        //   })
        //   this.setCheckedList(ary)
        // } else {
        //   this.setCheckedList([])
        // }
        this.checked = checked
      },
      setCheNoteList() {
        // let list = []
        // for (let i = 0; i < this.checkedList.length; i++) {
        //   for (let s = 0; s < this.note.length; s++) {
        //     for (let attr in this.note[s]) {
        //       if (this.checkedList[i] == attr) {
        //         list.push(this.note[s])
        //       }
        //     }
        //   }
        // }
        // this.setCheckedNoteList(list)
      },

      storeChange(e, storeIndex, goodsIndex) {
        let ary = this.defCheckedList
        let checked = e.mp.detail.current
        let target = ary[storeIndex]
        target.store.checked = checked
        this.$set(ary, storeIndex, target)
        ary[storeIndex].cart_ids.map(item => {
          item.checked = checked
        })
        this.defCheckedList = ary
      },
      /**
       * * 选中某个商品
       *
       * ?状态：
       * > 1、选中最后一个
       * > 2、选中第一个或者其他  
       */
      receiptChange(e, storeIndex, goodsIndex) {
        let ary = this.defCheckedList
        let checked = e.mp.detail.current
        let target = ary[storeIndex]
        target.cart_ids[goodsIndex].checked = e.mp.detail.current
        this.$set(ary, storeIndex, target)
        if (checked) {
          let counter = 0
          ary[storeIndex].cart_ids.map(item => {
            if (item.checked) {
              counter++
            }
          })
          if (counter >= ary[storeIndex].cart_ids.length) {
            ary[storeIndex].store.checked = true
          } else {
            ary[storeIndex].store.checked = false
          }
        } else {
          ary[storeIndex].store.checked = false
        }
        this.defCheckedList = ary
      },
      getStoreGoodsLength(store) {
        let length = 0;
        let store_id = store.store_id
        this.cartList.map((item) => {
          if (item.store_id == store_id) {
            item.goods.map(t => {
              length++
            })
          }
        })
        return length
      },
      // getStoreGoodsLength(store) {
      //   let length = 0;
      //   let store_id = store.store_id
      //   this.cartList.map((item) => {
      //     if (item.store_id == store_id) {
      //       item.goods.map(t => {
      //         length++
      //       })
      //     }
      //   })
      //   return length
      // },
      getCartLength() {
        let length = 0;
        this.cartList.map((item) => {
          item.goods.map(t => {
            length++
          })
        })
        return length
      },
      isAllChecked() {
        let counter = 0
        this.defCheckedList.map(item => {
          item.cart_ids.map(goods => {
            if (goods.checked) {
              counter++
            }
          })
        })
        let cartCounter = 0
        this.cartList.map(item => {
          item.goods.map(t => {
            cartCounter++
          })
        })
        if (counter == cartCounter) {
          return true
        }
        return false
      },
      reSetCheckedList() {
        let ary = []
        this.defCheckedList.map(item => {
          //console.log(item)
          let obj = {}
          obj.cart_ids = []
          item.cart_ids.map(goods => {
            if (goods.checked) {
              obj.cart_ids.push(goods.cart_id)
            }
          })
          if (obj.cart_ids.length > 0) {
            obj.store_id = item.store.store_id
            ary.push(obj)
          }
        })
        this.setCheckedList(ary)
      },
      getCheckedPrice() {
        let price = 0;
        this.cartList.map((item) => {
          item.goods.map(t => {
            this.defCheckedList.map(item => {
              item.cart_ids.map(goods => {
                if (goods.checked && goods.cart_id == t.cart_id) {
                  price += t.goods_price * t.goods_num
                }
              })
            })
          })
        })
        this.price = price
      }
    },
    // // 下拉刷新方法，与methods方法同级
    // async onPullDownRefresh() {
    //   // to doing..
    //   // 停止下拉刷新
    //   await this.getMallCartList()
    //   wx.stopPullDownRefresh();
    // },
    // // 上拉加载，拉到底部触发
    // onReachBottom() {
    //   // 到这底部在这里需要做什么事情
    //   // this.loadMore();
    // },
    onLoad() {
      console.log(111111111)
    },
    onUnload() {
      console.log(2222222222)
    },
    onShow() {
      console.log(33333333333)
      console.log(this.defCheckedList)
      this.defCheckedList=[]
      this.getMallCartList();
    },
    onHide() {
      console.log(44444444444)
      this.defCheckedList=[]
      // console.log(this.defCheckedList)
      // for (let i = 0; i < this.defCheckedList.length; i++) {
      //   this.defCheckedList[i].store.checked = false
      //   for (let s = 0; s < this.defCheckedList[i].cart_ids.length; s++) {
      //     this.defCheckedList[i].cart_ids[s].checked = false
      //   }
      // }
    },
    mounted() {
      this.getMallCartList();
    },
    watch: {
      defCheckedList() {
        if (this.defCheckedList.length > 0) {
          if (this.isAllChecked()) {
            this.checked = true
          } else {
            this.checked = false
          }
          this.getCheckedPrice()
          this.reSetCheckedList()
        }
      }
    }
  }

</script>

<style lang="less">
  .shoppingCart {
    padding-bottom: 46px;
  }

  .receipt-list {
    padding: 15px;

    .receipt {}
  }

  .receipt-nav {
    background: #fff;
    position: fixed;
    bottom: 46px;
    left: 0;
    right: 0;
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 46px;

    &:after {
      content: '';
      position: absolute;
      top: 0;
      left: 0;
      width: 200%;
      height: 200%;
      transform: scale(.5);
      transform-origin: 0 0;
      pointer-events: none;
      box-sizing: border-box;
      border: 0 solid #E9EAEC;
      border-top-width: 1px
    }
  }

  .receipt-control {
    display: flex;
    align-items: center;
    padding-left: 15px;

    .gxs-check {
      display: flex;
      align-items: center;

      p {
        font-size: 14px;
        color: #606060;
        z-index: 9;

      }
    }

    .checkbox {
      margin-right: 5px;
    }

    .delete {
      margin-left: 10px;
      font-size: 14px;
      color: #EE7559;
    }
  }

  .receipt-settlement {
    display: flex;
    align-items: center;
    padding-right: 15px;

    .total {
      font-size: 14px;
      color: rgba(96, 96, 96, 1);
    }

    .price {
      font-size: 15px;
      color: #EE7559;
      // margin-left: 5px;
    }

    .settlement-btn {
      width: 80px;
      height: 30px;
      line-height: 30px;
      background: rgba(238, 117, 89, 1);
      border-radius: 15px;
      font-size: 15px;
      color: rgba(255, 255, 255, 1);
      text-align: center;
      margin: 0;
      margin-left: 15px;
    }
  }

  .dialog-textarea {
    width: 100%;
    padding: 15px;
    font-size: 14px;
    color: #000;
    height: 100px;
    box-sizing: border-box;
  }

  .gxs-checkbox {
    label {
      display: flex;
      align-items: center;
    }
  }

  .receipt-check {
    width: 48px;
    height: 48px;
    overflow: hidden;
  }

  .receipt-store {
    background: #fff;
    border-radius: 5px;
    overflow: hidden;
    margin-top: 10px;

    .receipt-store-header {
      display: flex;
      position: relative;
      height: 38px;
      align-items: center;
      border-bottom: 1px solid #F8F8F8;
      overflow: hidden;

      .receipt-check {
        height: 34px;
      }

      // &:after {
      //   content: "";
      //   position: absolute;
      //   display: block;
      //   height: 1px;
      //   width: 100%;
      //   top: 0;
      //   left: 0;
      //   bottom: 0;
      //   background: #e9eaec;
      // }

      .store-name {
        margin-left: 10px;
        font-size: 14px;
        color: rgba(51, 51, 51, 1);
      }
    }

    .receipt-store-body {
      padding-bottom: 15px;
    }
  }

</style>
